import { loadCacheFromFile, saveCacheToFile, getDataFromCache, setDataToCache, translate } from './cacheResult';
import crpyto from 'crypto';
import { Parser } from 'htmlparser2';

export async function translateHtml(html: string) {
	let skip = false;
	let translatedHtml = `\n `;
	let translateDocument = ``;
	let htmlPreCode = `\n `;
	let docPosition = 0;
	loadCacheFromFile(); //从文件中加载缓存
	let parser = new Parser(
		{
			onopentag(name, attribs) {
				let attribString = '';
				for (const [key, value] of Object.entries(attribs)) {
					attribString += ` ${key}="${value}"`;
				}
				translatedHtml += `<${name}${attribString}>`;
				if (name === 'pre') {
					skip = true; // Set flag to skip content inside <pre> elements
				}
				if (name === 'code') {
					skip = true;
				}
			},
			ontext(text) {
				if (!skip) {
					translateDocument += text + '@';
					// result.push(translate(text))
					translatedHtml = translatedHtml + 'docPosition' + docPosition.toString();
					docPosition++;
				} else {
					htmlPreCode += text;
					translatedHtml += text;
				}
			},
			onclosetag(tagname) {
				translatedHtml += `</${tagname}>`;
				if (tagname === 'pre') {
					skip = false; // Reset flag when </pre> is encountered
				} else if (tagname === 'code') {
					skip = false;
				}
			},
		},
		{
			decodeEntities: true, // decode entities
		},
	);
	parser.write(html);
	parser.end();
	let result: string[] = [];
	let hash = crpyto.createHash('md5').update(JSON.stringify(translateDocument)).digest('hex');
	if (getDataFromCache(hash) !== null) {
		result = getDataFromCache(hash);
	} else {
		let ret = await translate(translateDocument);
		result = ret ? ret.split('@') : translateDocument;
		if (!ret) return result;
		setDataToCache(hash, result);
	}
	console.log(docPosition);
	let resultDocument = `\n `;
	console.log(result.length);
	let readline = require('readline');

	function askQuestion(query) {
		const rl = readline.createInterface({
			input: process.stdin,
			output: process.stdout,
		});

		return new Promise((resolve) => {
			rl.question(query, (answer) => {
				rl.close();
				resolve(answer);
			});
		});
	}
	// let answer = await askQuestion(' (y/n)');
	// console.log(translatedHtml);
	// await askQuestion(' (y/n)');
	// console.log(result);
	for (let i = 0; i <= docPosition; i++) {
		translatedHtml = translatedHtml.replace('docPosition' + i.toString(), result[i]); //replace是返回一个新字符串而不是修改原字符串
	}
	// await askQuestion(' (y/n)');

	// console.log(translatedHtml);
	// window.showInformationMessage(translatedHtml);
	return translatedHtml;
}
